package one.bugu.android.demon.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import com.juefeng.android.framework.LKUtil;
import one.bugu.android.demon.entity.SearchHistoryEntity;

import java.io.*;
import java.util.List;

/**
 * 文件操作工具类
 */
public class FileUtils {
    private FileUtils() {
    }

    /**
     * 递归文件
     */
    public static void recursionFile(File cacheFile, List<File> cacheFiles) {
        File[] files = cacheFile.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                recursionFile(file, cacheFiles);
            } else {
                cacheFiles.add(file);
            }
        }
    }

    /**
     * 删除文件
     */
    public static void deleteFile(String path) {
        new File(path).delete();
    }

    /**
     * 删除文件夹
     */
    public static void deleteDir(File file) {
        try {
            if (!file.exists()) {
                return;
            }
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File item : files) {
                    deleteDir(item);
                }
            } else {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 写文件
     */
    public static void write(Context context, String fileName, String content) {
        try {
            FileOutputStream out = new FileOutputStream(fileName, false);
            try {
                byte[] bytes = content.getBytes("GB2312");
                out.write(bytes);
                out.flush();
                out.close();
            } finally {
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 读文件
     */
    public static String read(Context context, String fileName) {
        try {
            File file = new File(fileName);
            if (!file.exists()) {
                return null;
            }
            FileInputStream in = new FileInputStream(file);
            try {
                byte[] bytes = new byte[1024];
                int count;
                StringBuilder stringBuilder = new StringBuilder();
                while (0 < (count = in.read(bytes))) {
                    stringBuilder.append(new String(bytes, 0, count, "GB2312"));
                }
                in.close();
                return stringBuilder.toString();
            } finally {
                in.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 写崩溃日志
     */
    public static void WriteCrashLog(File logFile, Throwable ex) throws Exception {
        PrintWriter writer = new PrintWriter(new FileWriter(logFile, true));
        try {
            ex.printStackTrace(writer);
            writer.flush();
        } finally {
            writer.close();
        }
    }


    /**
     * 把图片压缩
     */
    public static File compressFile(Context context, Bitmap bitmap) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, os);
        byte[] bytes = os.toByteArray();
        File file = null;
        try {
            file = FileUtils.getFileFromBytes(bytes, String.format("%s/%s%s", context.getExternalCacheDir(), System.currentTimeMillis(), ".jpg"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bitmap != null) {
                if (!bitmap.isRecycled()) {
                    bitmap.recycle();
                }
                bitmap = null;
            }
        }
        return file;
    }

    /**
     * 把字节数组保存为一个文件
     */
    private static File getFileFromBytes(byte[] b, String outputFile) {
        File ret = null;
        BufferedOutputStream stream = null;
        try {
            ret = new File(outputFile);
            FileOutputStream fstream = new FileOutputStream(ret);
            stream = new BufferedOutputStream(fstream);
            stream.write(b);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ret;
    }

    public static void cleanCache(Context mContext) {
        deleteDir(mContext.getCacheDir());
        deleteDir(LKUtil.getAppConfig().getExternalDownCacheDir());
        deleteDir(LKUtil.getAppConfig().getExternalImageCacheDir());
        LKUtil.getDBManager().dropTable(SearchHistoryEntity.class);
        LKUtil.getImageLoader().cleanCache();
    }


    public static String getExternalPublicImageDir(Context context) {
        File file = new File(Environment.getExternalStorageDirectory(), "布谷精灵/image/");
        if (!file.exists()) {
            file.mkdirs();
        }
        return file.getPath();
    }
}

